<template>
  <div class="app-container">
    <div class="app-title">查询条件</div>
    <div class="filter-container">
      活动标题:
      <el-input
        v-model="queryParams.title"
        :placeholder="$t('table.activity.title')"
        class="search-item"
      />
      活动状态
      <el-select v-model="queryParams.status" :placeholder="$t('table.activity.status')">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button v-has-permission="['ebrokerActivity:search']" class="" type="primary" @click="search">
        {{ $t("common.search") }}
      </el-button>
      <el-button class="" type="success" @click="reset">
        {{ $t("table.reset") }}
      </el-button>
      <el-button v-has-permission="['ebrokerActivity:add']" class="el-icon-folder-add" type="success" @click.native="add">
        {{ $t("table.add") }}
      </el-button>
    </div>
    <div class="app-title">活动列表</div>

    <el-table
      ref="table"
      :key="tableKey"
      v-loading="loading"
      :data="list"
      border
      fit
      style="width: 100%"
      @sort-change="sortChange"
    >
      <el-table-column
        :label="$t('table.activity.title')"
        prop="username"
        :show-overflow-tooltip="true"
        align="center"
        min-width="120px"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.activity.startTime')"
        :show-overflow-tooltip="true"
        align="center"
        prop="startTime"
        min-width="150px"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.startTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.activity.endTime')"
        :show-overflow-tooltip="true"
        align="center"
        min-width="150px"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.endTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.activity.length')"
        :show-overflow-tooltip="true"
        align="center"
        min-width="150px"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.duration }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.activity.mystatus')"
        :show-overflow-tooltip="true"
        align="center"
        min-width="150px"
      >
        <template slot-scope="scope">
          <span>{{ scope.row.status | filteActivity }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="主展示位置"
        :show-overflow-tooltip="true"
        align="center"
        min-width="150px"
      >
        <template slot-scope="scope">
          <span>{{
            scope.row.location === 1 ? "首页轮播bannner" : "首页轮播bannner"
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.activity.href')"
        :show-overflow-tooltip="true"
        align="center"
        min-width="150px"
      >
        <template slot-scope="scope">
          <a :href="scope.row.href" target="_blank" rel="noopener noreferrer" style="color:#00f">{{ scope.row.href }}</a>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('table.operation')"
        align="center"
        min-width="150px"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-link icon="el-icon-view" @click="view(row)">查看</el-link>
          <el-link
            v-if="row.status === 0 || row.status == 1 || row.status === 2"
            v-has-permission="['ebrokerActivity:update']"
            icon="el-icon-setting"
            @click="update(row)"
          >修改</el-link>
          <el-link
            v-if="row.status === 0 || row.status == 1 || row.status === 2"
            v-has-permission="['ebrokerActivity:update']"
            icon="el-icon-delete"
            @click="edit(row, '取消')"
          >取消</el-link>
          <el-link
            v-if="row.status == 1"
            v-has-permission="['ebrokerActivity:update']"
            icon="el-icon-delete"
            @click="edit(row, '暂停')"
          >暂停</el-link>
          <el-link
            v-if="row.status == 2 || row.status == -1"
            v-has-permission="['ebrokerActivity:update']"
            icon="el-icon-paperclip"
            @click="edit(row, '重启')"
          >重启</el-link>

          <!-- <el-link
            v-has-no-permission="['user:view', 'user:update', 'user:delete']"
            class="no-perm"
          >
            {{ $t("tips.noPermission") }}
          </el-link> -->
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="pagination.pageNum"
      :limit.sync="pagination.pageSize"
      @pagination="search"
    />
    <!--  添加弹框 -->
    <el-dialog
      title="新增运营活动"
      :width="width"
      :visible.sync="isVisible"
      class="user-view"
    >
      <el-form
        ref="ruleForm"
        :model="ruleForm"
        class="demo-ruleForm"
      >
        <el-form-item label="活动标题" required="">
          <el-input
            v-model="ruleForm.title"
            maxlength="15"
            placeholder="不超过15个字"
            style="width: 350px"
          />
        </el-form-item>
        <el-form-item label="活动时间" required>
          <el-date-picker
            v-model="ruleForm.startTime"
            placeholder="选择开始时间"
            value-format="yyyy-MM-dd HH:mm"
            class="filter-item search-item date-range-item"
            type="datetime"
          />
          -
          <el-date-picker
            v-model="ruleForm.endTime"
            placeholder="选择结束时间"
            value-format="yyyy-MM-dd HH:mm"
            class="filter-item search-item date-range-item"
            type="datetime"
          />
        </el-form-item>
        <el-form-item label="展示位置" prop="location" required="">
          <el-radio
            v-model="radio"
            label="1"
            checked
          >APP banner(750x470)
          </el-radio>
        </el-form-item>
        <el-form-item label="图片" prop="pic" required="">
          <p class="small">
            需要一张主图片及备用图片，当有足够多的活动时会用主图片，当只有一个活动时，为了保持美观，将展示图片
          </p>
          <el-upload
            class="avatar-uploader"
            :action="baseUrl"
            :show-file-list="false"
            :headers="headers"
            :on-error="handleError"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="imageUrl"
              :src="imageUrl"
              class="avatar"
              style="width: 150px; height: 150px; margin-top: 5px"
            >
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="跳转链接">
          <p class="small">
            外部链接直接输入网址，内置页面或位置需要查询技术链接地址
          </p>
          <el-input
            v-model="ruleForm.href"
            placeholder="请输入链接"
            style="width: 400px"
          />
        </el-form-item>
        <el-form-item label="优先级">
          <p class="small">输入0-100的整数，数字越小位置靠前</p>
          <el-input
            v-model="ruleForm.priority"
            type="number"
            max="100"
            style="width: 420px"
            @keyup.native="proving"
          />
        </el-form-item>
        <el-form-item style="text-align: right">
          <el-button
            type="primary"
            style="text-align: right"
            @click="submitForm('ruleForm')"
          >提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <!-- 编辑数据 -->
    <el-dialog
      title="编辑运营活动"
      :width="width"
      :visible.sync="editEdVisible"
      class="user-view"
    >
      <el-form ref="editForm" :model="editRuleForm" class="demo-ruleForm">
        <el-form-item label="活动标题" required>
          <el-input
            v-model="editRuleForm.title"
            placeholder="不超过15个字"
            style="width: 350px"
          />
        </el-form-item>
        <el-form-item label="活动时间" required>
          <el-date-picker
            v-model="editRuleForm.startTime"
            placeholder="选择开始时间"
            value-format="yyyy-MM-dd HH:mm"
            class="filter-item search-item date-range-item"
            type="datetime"
          />
          -
          <el-date-picker
            v-model="editRuleForm.endTime"
            placeholder="选择结束时间"
            value-format="yyyy-MM-dd HH:mm"
            class="filter-item search-item date-range-item"
            type="datetime"
          />

        </el-form-item>
        <el-form-item label="展示位置" required>
          <el-radio
            v-model="radio"
            label="1"
            checked
          >APP banner(750x470)
          </el-radio>
        </el-form-item>
        <el-form-item label="图片" prop="pic" required>
          <p class="small">
            需要一张主图片及备用图片，当有足够多的活动时会用主图片，当只有一个活动时，为了保持美观，将展示图片
          </p>
          <el-upload
            class="avatar-uploader"
            :action="baseUrl"
            :show-file-list="false"
            :headers="headers"
            :on-success="handleAvatarSuccess"
            :on-error="handleError"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="imageUrl"
              :src="imageUrl"
              class="avatar"
              style="width: 150px; height: 150px; margin-top: 20px"
            >
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="跳转链接" prop="href">
          <p class="small">
            外部链接直接输入网址，内置页面或位置需要查询技术链接地址
          </p>
          <el-input
            v-model="editRuleForm.href"
            placeholder="请输入链接"
            style="width: 400px"
          />
        </el-form-item>
        <el-form-item label="优先级" prop="href">
          <p class="small">输入0-100的整数，数字越小位置靠前</p>
          <el-input
            v-model="editRuleForm.priority"
            placeholder="请输入链接"
            maxlength="100"
            type="number"
            style="width: 420px"
            @keyup.native="provings"
          />
        </el-form-item>
        <el-form-item style="text-align: right">
          <el-button type="primary" style="text-align: right" @click="handleUpdate()">确定</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <updateActivity :title="title" :dialog-visible="updatedialogVisible" :content="content" @fnclose="fnclose" />
  </div>
</template>
<script>
import Pagination from '@/components/Pagination'
import updateActivity from './updateActivity.vue'
import { countDown, countDownEnd } from '@/utils'
import { parseTime } from '@/utils'
import crypto from 'crypto-js'
const appkey = 'Sz7Jo5M4T1smiHgS'
// eslint-disable-next-line radix
const timestamp = parseInt(Date.now() / 1000)
const nonceStr = 'HBxcnRjX'

export default {
  components: {
    Pagination,
    updateActivity
  },
  data() {
    return {
      radio: '1',
      ruleForm: {
        id: 0,
        title: '',
        startTime: '',
        endTime: '',
        location: '1',
        href: '',
        imageUrl: '',
        priority: '',
        source: 1
      },
      editRuleForm: {
        title: '',
        startTime: '',
        endTime: '',
        location: '1',
        href: '',
        imageUrl: '',
        priority: '',
        source: 1
      },
      imageUrl: '',
      options: [
        {
          label: '全部活动',
          value: ''
        },
        {
          label: '未开始',
          value: '0'
        },
        {
          label: '进行中',
          value: '1'
        },
        {
          label: '已暂停',
          value: '2'
        },
        {
          label: '已结束',
          value: '3'
        },
        {
          label: '已取消',
          value: '-1'
        }
      ],
      isVisible: false,
      title: '',
      editEdVisible: false,
      tableKey: 0,
      loading: false,
      total: 0,
      queryParams: {},
      pagination: {
        pageSize: 10,
        pageNum: 1
      },
      width: '700px',
      list: [
        {
          activityLogs: null,
          createBy: '15102045416',
          createTime: '2021-06-15 18:26:32',
          duration: '15天0小时0分',
          endTime: '2021-07-12 17:44:00',
          href: '222',
          id: 1,
          imageUrl: 'http://wwww.baidu.com',
          isDel: 0,
          location: 1,
          priority: 3,
          source: 0,
          startTime: '2021-07-18 16:05:00',
          status: 2,
          title: '333',
          updateBy: '15102045416',
          updateTime: '2021-06-11 19:14:23'
        }
      ],
      headers: {
        Authorization: null
      },
      updatedialogVisible: false,
      content: {},
      baseUrl: process.env.VUE_APP_BASE_API + '/web/upload/bigFile?source=web&type=active'
    }
  },
  mounted() {
    const temp = [appkey, timestamp, nonceStr, encodeURIComponent(this.baseUrl)].sort()
    const myTemp = temp.join('')
    const hmacSHA256 = crypto.HmacSHA256(myTemp, '2ac16dc294046ed43a87d70ad8cb08013fab0b57')
    const signature = crypto.enc.Base64.stringify(hmacSHA256)
    const signs = `appkey=${appkey},timestamp=${timestamp},nonceStr=${nonceStr},sign=${signature},data=${encodeURIComponent(this.baseUrl)}`
    const tokens = `${crypto.MD5(signs)}`
    this.headers = {
      Authorization: `bearer ${this.$store.state.account.accessToken}`,
      channel: '00',
      application: '02',
      source: 5,
      appkey,
      nonceStr,
      timestamp,
      sign: tokens

    }
    this.fetch()
  },
  methods: {
    submitForm(formName) {
      if (this.ruleForm.title === '') {
        this.$message.error('请输入活动标题')
        return
      }
      if (this.ruleForm.startTime === '' || this.ruleForm.endTime === '') {
        this.$message.error('请选择活动时间')
        return
      }
      if (new Date(this.ruleForm.endTime).getTime() - new Date(this.ruleForm.startTime).getTime() < 0) {
        this.$message.error('开始时间不能大于结束时间')
        return
      }
      if (this.ruleForm.imageUrl === '') {
        this.$message.error('请上传图片')
        return
      }

      this.$post('/web/activity', { ...this.ruleForm }, 'json').then(
        (res) => {
          if (res.data.code === '0') {
            this.ruleForm = {}
            this.isVisible = false
            this.fetch()
            this.imageUrl = ''
            this.$message.success('添加成功')
          } else {
            this.$message.error(res.data.message)
          }
        }
      )
    },
    handleError() {
      this.$message.error('图片上传失败')
    },
    update(row) {
      this.editEdVisible = true
      row.location = '1'
      this.editRuleForm = JSON.parse(JSON.stringify(row))
      this.imageUrl = this.editRuleForm.imageUrl
    },
    edit(row, title) {
      row.tips = title
      this.content = row
      this.updatedialogVisible = true
    },
    handleUpdate() {
      this.editRuleForm.startTime = parseTime(this.editRuleForm.startTime, '{y}-{m}-{d} {h}:{i}')
      this.editRuleForm.endTime = parseTime(this.editRuleForm.endTime, '{y}-{m}-{d} {h}:{i}')
      if (this.editRuleForm.title === '') {
        this.$message.error('请输入活动标题')
        return
      }
      if (this.editRuleForm.startTime === '' || this.editRuleForm.endTime === '') {
        this.$message.error('请选择活动时间')
        return
      }
      if (new Date(this.editRuleForm.endTime).getTime() - new Date(this.editRuleForm.startTime).getTime() < 0) {
        this.$message.error('开始时间不能大于结束时间')
        return
      }
      if (this.editRuleForm.imageUrl === '') {
        this.$message.error('请上传图片')
        return
      }

      const { startTime, endTime, id, location, priority, href, source, imageUrl, title } = this.editRuleForm
      this.$put('/web/activity', { startTime, endTime, id, location, priority, href, source, imageUrl, title }, 'json').then((res) => {
        if (res.data.code === '0') {
          this.$message.success('编辑活动成功')
          this.$refs.editForm.resetFields()
          this.fetch()
          this.imageUrl = ''
          this.editEdVisible = false
        } else {
          this.$message.error(res.data.message)
        }
      })
    },
    search() {
      this.fetch({
        ...this.queryParams
      })
    },
    reset() {
      this.queryParams = {}
      this.search()
    },
    add() {
      this.isVisible = true
      this.imageUrl = ''
    },
    handleAvatarSuccess(res, file) {
      console.log(res)
      if (this.editEdVisible) {
        if (res.code === '0') {
          this.imageUrl = res.data
          this.editRuleForm.imageUrl = res.data
        }
      } else {
        if (res.code === '0') {
          this.imageUrl = res.data
          this.ruleForm.imageUrl = res.data
        }
      }
    },
    beforeAvatarUpload(file) {
      const _this = this
      const isLt2M = file.size / 1024 / 1024 < 2
      const isImge = file.type.indexOf('image') !== -1
      const isSize = new Promise(function(resolve, reject) {
        const width = 750 // 限制图片尺寸为654X270
        const height = 470
        const _URL = window.URL || window.webkitURL
        const img = new Image()
        img.onload = function() {
          const valid = img.width === width && img.height === height
          valid ? resolve() : reject()
        }
        img.src = _URL.createObjectURL(file)
      }).then(() => {
        return file
      }, () => {
        _this.$message.error('图片尺寸限制为750*470')
        return Promise.reject()
      })
      if (!isImge) {
        this.$message.error('请上传图片格式')
      }
      if (!isLt2M) {
        this.$message.error('上传活动图片大小不能超过 2MB!')
      }
      return isSize || isImge || isLt2M
    },
    fetch(params = {}) {
      params.pageSize = this.pagination.pageSize
      params.pageNum = this.pagination.pageNum
      const { status, title } = this.queryParams
      this.loading = true
      this.$post(
        '/web/activity/list',
        {
          queryRequest: {
            pageSize: this.pagination.pageSize,
            pageNum: this.pagination.pageNum,
            field: 'createTime',
            order: 'descending'
          },
          entity: {
            source: 1,
            status,
            title
          }
        },
        'json'
      ).then((r) => {
        const data = r.data.data
        this.total = data.total
        this.list = data.records
        this.list.forEach((item) => {
          if (item.status === 0) {
            item.startTime = countDown(item.startTime, item) || item.startTime
          }
          if (item.status === 1) {
            item.endTime = countDownEnd(item.endTime, item) || item.endTime
          }
        })
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    sortChange(val) {
      this.sort.field = val.prop
      this.sort.order = val.order
      this.search()
    },
    view(row) {
      this.$router.push({
        name: 'careActivityDetail',
        query: {
          id: row.id
        }
      })
    },
    proving() {
      this.ruleForm.priority = this.ruleForm.priority.replace(/[^\.\d]/g, '')
      this.ruleForm.priority = this.ruleForm.priority.replace('.', '')
      if (this.ruleForm.priority > 100) {
        this.ruleForm.priority = 100
      }
    },
    provings() {
      this.editRuleForm.priority = this.editRuleForm.priority.replace(/[^\.\d]/g, '')
      this.editRuleForm.priority = this.editRuleForm.priority.replace('.', '')
      if (this.editRuleForm.priority > 100) {
        this.editRuleForm.priority = 100
      }
    },
    fnclose(e) {
      if (e && e.isSearch) {
        this.fetch()
      }
      this.updatedialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.small {
  font-size: 11px;
  line-height: 1;
  margin-bottom: 5px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  border: 1px dashed #ccc;
  width: 158px;
  height: 158px;
  border-radius: 15px;
  line-height: 158px;
  text-align: center;
}
.avatar {
  width: 158px;
  height: 158px;
  display: block;
}
</style>
